package com.msb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author sunpeng
 * @Date 2021-06-07 9:12
 */


@Controller
public class TransAttribute {

    /*
1.request
2.session
3.context
*/
    @GetMapping("/setData")
    public String setData(HttpServletRequest request, HttpSession session){
        request.setAttribute("message", "request success");
        session.setAttribute("message", "session success");
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("message", "context success");
        return "/showDataPage.jsp";
    }

    //view
    @GetMapping("/modelData")
    public String modelData(Model model){
        model.addAttribute("message", "model");
        //return "/showDataPage.jsp"; //request域
        return "redirect:/showDataPage.jsp"; //http://localhost:8090/springmvc_first_war_exploded/showDataPage.jsp?message=model
        //特别，servlet重定向本来不可以传输数据，springmvc进行封装把数据放到参数里
    }

    //ModelAndView
    //返回ModelAndView才生效，这点和view不一样
    @GetMapping("/mvData")
    public ModelAndView mvData(){
        ModelAndView mv = new ModelAndView();
        Map<String, Object> model = mv.getModel();
        model.put("message", "hello mv");
        mv.setViewName("/showDataPage.jsp");
        return mv;
    }
}
